package com.home.jsonhelpers;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;

import com.home.rhtester.R;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class JsonArrayAdapter extends BaseAdapter {
	
	
	protected ArrayList<ResourceEntry> entries;
	protected Context context;
	protected int imageResource;
	protected int row_style;
	
	
	
	public JsonArrayAdapter(JSONArray jsonArray,Context context,String jsonNameKey,String jsonIdKey,int imageId,int row_layout_style) throws JSONException {
		
		entries=new ArrayList<ResourceEntry>();
		this.context=context;
		imageResource=imageId;
		row_style=row_layout_style;
		fillArray(jsonArray, jsonNameKey, jsonIdKey);
	}

	protected void fillArray(JSONArray jsonArray, String jsonNameKey, String jsonIdKey) throws JSONException {
		for (int i=0;i<jsonArray.length();i++)
		{
			JSONObject obj=jsonArray.getJSONObject(i);
			String name=obj.getString(jsonNameKey);
			int id=obj.getInt(jsonIdKey);
			ResourceEntry entry=new ResourceEntry(name, id, obj);
			entries.add(entry);
		}
	}

	@Override
	public int getCount() {
		
		return entries.size();
	}

	@Override
	public Object getItem(int postion) {
		return entries.get(postion);
	}

	@Override
	public long getItemId(int position) {
		return entries.get(position).id;
	}

	@Override
	public View getView(int arg0, View arg1, ViewGroup arg2) {
		View v=arg1;
		
		if (v==null)
		{
			ResourceEntry entry=entries.get(arg0);
			LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(row_style, null);
            TextView tv1=(TextView)v.findViewById(R.id.row_title);
            ImageView img=(ImageView)v.findViewById(R.id.row_img);
            tv1.setText(entry.name);
            img.setImageResource(imageResource);
          //  tv2.setText(entry.id);
		}
		return v;

	}

}
